﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;


namespace Microsoft.SharePoint
{
    public static class Extentions
    {
        public static void RegisterEventReceiver<TR>(this SPList self, SPEventReceiverType type, SPEventReceiverSynchronization sync, int sequence) where TR : SPItemEventReceiver
        {
            var receiverType = typeof(TR);

            if (self.EventReceivers.Cast<SPEventReceiverDefinition>()
                .Any(erd => erd.Assembly == receiverType.Assembly.FullName
                    && erd.Class == receiverType.FullName
                    && erd.Name == receiverType.FullName
                    && erd.Synchronization == sync
                    && erd.SequenceNumber == sequence
                    && erd.Type == type)) return;

            var er = self.EventReceivers.Add();

            er.Type = type;
            er.Assembly = receiverType.Assembly.FullName;
            er.Class = receiverType.FullName;
            er.Name = receiverType.FullName;
            er.SequenceNumber = sequence;
            er.Synchronization = sync;
            er.Update();
        }
        
        /// <summary>
        /// Default values of synchronisation:Synchronous and sequence:10000
        /// </summary>
        public static void RegisterEventReceiver<TR>(this SPList self, SPEventReceiverType type) where TR : SPItemEventReceiver
        {
            var receiverType = typeof(TR);
            var sync = SPEventReceiverSynchronization.Synchronous;
            int sequence = 10000;
            RegisterEventReceiver<TR>(self, type, sync, sequence);
        }

        /// <summary>
        /// Default values of synchronisation:Synchronous
        /// </summary>
        public static void RegisterEventReceiver<TR>(this SPList self, SPEventReceiverType type, int sequence) where TR : SPItemEventReceiver
        {
            var receiverType = typeof(TR);
            var sync = SPEventReceiverSynchronization.Synchronous;
            RegisterEventReceiver<TR>(self, type, sync, sequence);
        }
    }
}
